﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Facebook;
using System.Web.Security;
using BLL;
using BO;

namespace MvcApplication1.Controllers
{
    public class FacebookController : Controller
    {
        private const string logoffUrl = "http://localhost:3000/";
        private const string redirectUrl = "http://localhost:3000/Facebook/Callback";

        public ActionResult OAuth(string returnUrl)
        {
            var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current);
            oAuthClient.RedirectUri = new Uri(redirectUrl);

            var loginUri = oAuthClient.GetLoginUrl(new Dictionary<string, object> { { "state", "state_" }, { "scope", "offline_access,manage_pages,publish_stream" } });
            return Redirect(loginUri.AbsoluteUri);
        }
        
        public ActionResult Callback(string code, string state)
        {
            FacebookOAuthResult oauthResult;
            if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult))
            {
                if (oauthResult.IsSuccess)
                {
                    var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current);
                    oAuthClient.RedirectUri = new Uri(redirectUrl);
                    dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
                    string accessToken = tokenResult.access_token;

                    DateTime expiresOn = DateTime.MaxValue;

                    FacebookClient fbClient = new FacebookClient(accessToken);
                    dynamic me = fbClient.Get("me?fields=id,name");
                    long facebookId = Convert.ToInt64(me.id);

                    var account = Accounts.Get().Where(Accounts.Columns.ForeignID, Actions.Equal, facebookId).SelectOne();
                    if (account == null)
                    {
                        account = new Account { FBKey = accessToken, Name = me.name, ForeignID = facebookId.ToString() };
                        account.Insert();
                    }
                    else
                    {
                        account.FBKey = accessToken;
                        account.Name = me.name;
                        account.Update();
                    }
                    dynamic pages = fbClient.Get("me/accounts");
                    foreach (var p in pages.data)
                    {
                        FBPage page = FBPages.Get().Where(FBPages.Columns.ForeignID, Actions.Equal, p.id).SelectOne();
                        if (page == null)
                        {
                            page = new FBPage { ForeignID = p.id, Name = p.name, Token = p.access_token };
                            page.Insert();
                        }
                        else
                        {
                            page.Name = p.name;
                            page.Token = p.access_token;
                            page.Update();
                        }
                    }



                    ViewBag.Name = account.Name;
                }
            }

            
            return View();
        }

        public ActionResult Pages(String key)
        {
            FacebookClient fbClient = new FacebookClient(key);
            dynamic me = fbClient.Get("me?fields=id,name");
            long facebookId = Convert.ToInt64(me.id);

            return null;
        }

        public ActionResult User()
        {
            var account = Accounts.Get().Where(Accounts.Columns.FBKey, Actions.NotEqual, null).SelectOne();

            FacebookClient fbClient = new FacebookClient(account.FBKey);
            dynamic me = fbClient.Get("me?fields=id,name");
            long facebookId = Convert.ToInt64(me.id);

            return null;
        }

        public ActionResult Post()
        {
            var pages = FBPages.Get().Join(Posts.Get(), Posts.Columns.PageID).Select();
            foreach (var p in pages)
            {
                FacebookClient fbClient = new FacebookClient(p.Token);
                if (p.Posts != null && p.Posts.Count > 0)
                    fbClient.Post(string.Format("{0}/comments", p.Posts[0].ForeignID), new { message = "my first post" });
                else
                    fbClient.Post(string.Format("{0}/feed", p.ForeignID), new { message="my first post"});
            }

            return null;
        }
    }
}
